#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
获取Cloudflare Tunnel公共URL
"""

import subprocess
import time
import re
import os

def get_tunnel_url():
    """获取隧道URL"""
    print("🔍 检查Cloudflare Tunnel状态...")
    
    # 检查cloudflared进程
    try:
        result = subprocess.run(['tasklist', '/FI', 'IMAGENAME eq cloudflared.exe'], 
                              capture_output=True, text=True)
        if result.returncode == 0 and 'cloudflared.exe' in result.stdout:
            print("✅ cloudflared进程正在运行")
        else:
            print("❌ cloudflared进程未运行")
            return None
    except Exception as e:
        print(f"❌ 检查进程失败: {e}")
        return None
    
    # 尝试从日志或输出中获取URL
    print("🌐 尝试获取隧道URL...")
    
    # 方法1: 检查是否有日志文件
    log_files = [f for f in os.listdir('.') if 'cloudflared' in f.lower() and f.endswith('.log')]
    if log_files:
        print(f"📄 找到日志文件: {log_files}")
        for log_file in log_files:
            try:
                with open(log_file, 'r', encoding='utf-8') as f:
                    content = f.read()
                    # 查找URL模式
                    url_match = re.search(r'https://[a-zA-Z0-9-]+\.trycloudflare\.com', content)
                    if url_match:
                        url = url_match.group(0)
                        print(f"✅ 从日志文件找到URL: {url}")
                        return url
            except Exception as e:
                print(f"❌ 读取日志文件失败: {e}")
    
    # 方法2: 尝试启动新的隧道并获取URL
    print("🚀 启动新的隧道测试...")
    try:
        # 启动隧道进程
        process = subprocess.Popen(
            ['.\\cloudflared.exe', 'tunnel', '--url', 'localhost:8081'],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )
        
        # 等待一段时间让隧道启动
        time.sleep(10)
        
        # 检查输出
        if process.poll() is None:  # 进程仍在运行
            print("✅ 隧道进程启动成功")
            
            # 尝试从stderr读取URL（cloudflared通常将URL输出到stderr）
            try:
                stderr_output = process.stderr.read()
                if stderr_output:
                    url_match = re.search(r'https://[a-zA-Z0-9-]+\.trycloudflare\.com', stderr_output)
                    if url_match:
                        url = url_match.group(0)
                        print(f"✅ 找到隧道URL: {url}")
                        process.terminate()
                        return url
            except:
                pass
            
            # 如果无法从stderr读取，尝试从stdout读取
            try:
                stdout_output = process.stdout.read()
                if stdout_output:
                    url_match = re.search(r'https://[a-zA-Z0-9-]+\.trycloudflare\.com', stdout_output)
                    if url_match:
                        url = url_match.group(0)
                        print(f"✅ 找到隧道URL: {url}")
                        process.terminate()
                        return url
            except:
                pass
            
            print("⚠️ 无法从进程输出中获取URL")
            process.terminate()
            
        else:
            print("❌ 隧道进程启动失败")
            stdout, stderr = process.communicate()
            print(f"stdout: {stdout}")
            print(f"stderr: {stderr}")
            
    except Exception as e:
        print(f"❌ 启动隧道失败: {e}")
    
    # 方法3: 检查当前目录下的配置文件
    print("📁 检查配置文件...")
    config_files = [f for f in os.listdir('.') if 'tunnel' in f.lower() and f.endswith('.json')]
    if config_files:
        print(f"📄 找到配置文件: {config_files}")
        for config_file in config_files:
            try:
                with open(config_file, 'r', encoding='utf-8') as f:
                    content = f.read()
                    # 查找URL模式
                    url_match = re.search(r'https://[a-zA-Z0-9-]+\.trycloudflare\.com', content)
                    if url_match:
                        url = url_match.group(0)
                        print(f"✅ 从配置文件找到URL: {url}")
                        return url
            except Exception as e:
                print(f"❌ 读取配置文件失败: {e}")
    
    print("❌ 无法获取隧道URL")
    return None

def main():
    """主函数"""
    print("🔍 Cloudflare Tunnel URL 获取工具")
    print("=" * 50)
    
    url = get_tunnel_url()
    
    if url:
        print(f"\n🎯 隧道URL: {url}")
        print(f"🌐 WebSocket URL: {url.replace('https://', 'wss://')}")
        
        # 保存到文件
        with open('tunnel_url.txt', 'w', encoding='utf-8') as f:
            f.write(f"HTTPS: {url}\n")
            f.write(f"WSS: {url.replace('https://', 'wss://')}\n")
        
        print("💾 URL已保存到 tunnel_url.txt")
        
        return url
    else:
        print("\n❌ 无法获取隧道URL")
        print("💡 建议:")
        print("1. 手动运行: .\\cloudflared.exe tunnel --url localhost:8081")
        print("2. 复制显示的 https://xxx.trycloudflare.com")
        print("3. 将其转换为 wss://xxx.trycloudflare.com")
        return None

if __name__ == "__main__":
    main() 